<template>
  <div ref="eChartSalesRef" style="width: 100%; height: 400px"></div>
</template>
<script setup lang="ts">
import { onMounted, onUnmounted, ref, watch } from 'vue'
import * as echarts from 'echarts'
const eChartSalesRef = ref<HTMLDivElement | null>(null)
const props = defineProps({
  data: {
    type: Object,
    default: () => {
      return {
        xData: [],
        yData: [],
      }
    },
  },
})
let myChart = null as any
const init = () => {
  const xDataTemp = [] as any
  const yDataTemp = [] as any
  for(let i = 1; i <= 12; i ++) {
    xDataTemp.push(`2024-${i < 10 ? '0' + i : i}`)
    yDataTemp.push(Math.floor(Math.random() * 1000))
  }
  myChart = echarts.init(eChartSalesRef.value!)
  myChart.setOption({
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: xDataTemp,
    },
    yAxis: {
      type: 'value',
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985',
        },
      },
    },
    grid: {
      left: '3%',
      right: '3%',
      bottom: '4%',
      top: '4%',
      containLabel: true,
    },
    series: [
      {
        data: yDataTemp,
        type: 'line',
        smooth: true,
        lineStyle: {
          width: 0,
        },
        emphasis: {
          focus: 'series',
        },
        showSymbol: false,
        areaStyle: {
          opacity: 0.8,
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: '#1456f0',
            },
            {
              offset: 1,
              color: '#fff',
            },
          ]),
        },
      },
    ],
  })
}

const handleResize = () => {
  if (myChart) {
    myChart.resize()
  }
}

watch(
  () => props.data,
  () => {
    myChart.setOption({
      xAxis: {
        type: 'category',
        data: props.data.xData,
      },
      series: [
        {
          data: props.data.yData,
        },
      ],
    })
  }
)
onMounted(() => {
  init()
  window.addEventListener('resize', handleResize)
})
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  if (myChart) {
    myChart.dispose()
  }
})
</script>
<style scoped lang="scss"></style>
